package com.jrx.anytxn.transaction.job.coupon.step;

import com.jrx.anytxn.customer.entity.CmCustomerRightInfo;
import com.jrx.anytxn.customer.entity.TlRightsExchangeLog;
import com.jrx.anytxn.customer.service.ICustomerRightService;
import com.jrx.anytxn.customer.service.IRightsExchangeLogService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.enums.OrderStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName CouponOrderStateUpdateWriter
 *
 * @author lujianyou
 * @version 1.0
 * @description 权益订单状态更新 批处理Writer
 * @date 2021/11/29 16:41
 **/
@Service
@StepScope
public class CouponOrderStateUpdateWriter implements ItemWriter<TlRightsExchangeLog> {

    private static final Logger logger = LoggerFactory.getLogger(CouponOrderStateUpdateWriter.class);

    @Autowired
    ICustomerRightService iCustomerRightService;

    @Autowired
    IRightsExchangeLogService rightsExchangeLogService;

    @Override
    public void write(List<? extends TlRightsExchangeLog> items) throws Exception {
        for (TlRightsExchangeLog item : items) {
            rightsExchangeLogService.update(item);

            if (OrderStateEnum.FAIL.getCode().equals(item.getOrderState())) {
                CmCustomerRightInfo customerRightInfo = iCustomerRightService.findRightInfoByExchangeLogId(item.getCustomerId(), item.getTenantId(), item.getId());
                if (customerRightInfo == null) {
                    logger.error("权益状态更新异常，未查询到关联的权益资格记录，tl_rights_exchange_log.id：{}", item.getId());
                } else {
                    // 重置客户权益兑换资格
                    iCustomerRightService.resetRightToUnused(customerRightInfo);
                }
            }
        }
    }
}
